'use strict';

const Service = require('egg').Service;

class WanxiangService extends Service {
  async generate({ prompt, ratio, n }) {
    const { ctx, app } = this;
    
    // 转换比例为宽高
    let width, height;
    switch (ratio) {
      case '16:9':
        width = 1024;
        height = 576;
        break;
      case '9:16':
        width = 576;
        height = 1024;
        break;
      default: // 1:1
        width = 1024;
        height = 1024;
    }

    try {
      const response = await ctx.curl(app.config.wanxiang.apiUrl + '/v1/text2image/generation', {
        method: 'POST',
        contentType: 'json',
        dataType: 'json',
        headers: {
          'Authorization': `Bearer ${app.config.wanxiang.apiKey}`
        },
        data: {
          model: 'wanxiang-v1',
          prompt,
          n,
          width,
          height,
          response_format: 'url'
        },
        timeout: 60000, // 考虑到生成时间，设置较长的超时时间
      });

      if (response.status !== 200) {
        throw new Error(response.data.error || '请求失败');
      }

      return {
        images: response.data.data
      };
    } catch (error) {
      this.ctx.logger.error('[WanxiangService] generate error:', error);
      throw error;
    }
  }
}

module.exports = WanxiangService;
